%{
#include <stdio.h>
#include "../include/define.h"
#include "../include/parseGame.h"

char first[MAX_ELEMENT_NAME];
char second[MAX_ELEMENT_NAME];

%}

LETTER [A-Za-z]

SPACE [ ]

PLUS ["+"]

ENTER [\n]

FIRSTELEMENTNAME ({LETTER}+{SPACE}*{ENTER}*)+

SECONDELEMENTNAME {PLUS}({ENTER}*{SPACE}*)*({LETTER}+{SPACE}*)+{ENTER}

%%

{FIRSTELEMENTNAME}/{PLUS} {
	
	int i, j;
	
	for(i = 0, j = 0; yytext[i] != '\0' && yytext[i] != '+'; i++) {
		if(yytext[i] != '\n') {
			if(yytext[i] == '\t') {
				first[j] = ' ';			
			} else {
				first[j] = yytext[i];
				j++;
			}
		}
	}
	
	first[j] = '\0';
	j --;
	
	for(; first[j] == ' '; j--) {
		first[j] = '\0';
	}
	
}

{SECONDELEMENTNAME} {
	
	int i, j;
	
	for(i = 1, j = 0; yytext[i] != '\0'; i++) {
		if(yytext[i] != '\n') {
			if(yytext[i] == '\t') {
				second[j] = ' ';			
			} else {
				second[j] = yytext[i];
				j++;
			}
		}
	}
	
	second[j] = '\0';
	j --;
	
	for(; second[j] == ' '; j--) {
		second[j] = '\0';
	}
	
	for(i = 0; second[i] == ' '; i++);
	
	for(j = 0; second[j] != '\0'; j++) {
		second[j] = second[j + i];
	}
	
	doMagic();
}


. {}
\n {}

%%

int yywrap() {
	return(1);
}

void game()
{
	yylex();
	  
}

int getElementIndex(char * e) {
	int i;
	for(i = 0; elements[i].name != NULL; i++) {
		if(strcmp(elements[i].name, e)==0) {
			return i+1;
		}
	}
	return -1;
}

void doMagic() {

	int el1=getElementIndex(first);
	int el2=getElementIndex(second);
	
	if(el1==-1 || el2== -1){
		printf("???\n");
	}else{
		int j, flag=1;
		for(j = 0; magics[j].generated != NULL && flag; j ++) {
			if( ((strcmp(magics[j].e1->name, first)==0) && (strcmp(magics[j].e2->name, second)==0))
			    || ((strcmp(magics[j].e1->name, second)==0) && (strcmp(magics[j].e2->name, first)==0))){
				printf("%s\n", magics[j].generated->name);
				flag=0;
			}
		}
		if(flag){
			printf("???\n");
		}
	}
}
